import { useEffect, useMemo, useState } from 'react';
import { connect, history } from 'umi';
import { Card, Table, Divider, Button, Spin, message } from 'antd';
import pageStyles from '@/common/pageLayout.less';
import { DetailTableColumns } from '../mconfig';
import Cls from 'classnames';
import { getKeyRouter, tooltipLength } from '@/utils';
import { AuditModal } from './AuditModal';
import { DeliveredProcedureOutlined } from '@ant-design/icons';
import { PlanMaterialInfoServices, detailPlanServices } from '../services';
import '../common/style.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import MaterialDetailDrawer from '../../Acomponents/MaterialDetailDrawer';
import { formatDecimal } from '@/common';
const DetailsView = ({ curRes, locationProps }: Record<string, any>) => {
  /** 结构路由传参 */
  const {
    state: { PlanInfo },
  } = locationProps;
  /** 样式类名 */
  const prefixCls = 'plan-detail-';
  /** 详情对象 */
  const [recordObj, setRecordObj] = useState<Record<string, any>>({});
  /** 详情接口返回的物料数据 */
  const [MaterialList, setMaterialList] = useState<any[]>([]);
  /** 多选列表id */
  const [selectKeys, setSelectKeys] = useState<any[]>([]);
  /** id */
  const [pageRouterDomID, _setPageRouterDomID] = useState<string>(`planUpdateView-imageBox-${getKeyRouter()}`);
  /** 表格servicers */
  // const { reloadRequest, loading } = PlanMaterialInfoServices(curRes);
  /** 是否显示物料详情的 */
  const [isShowDrawer, setIsShowDrawer] = useState<Record<string, any>>({
    isShow: false,
    id: null,
  });

  /** 计划详情 */
  const { detailPlanRun, detailPlanLoading } = detailPlanServices((res: any) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      setRecordObj(res?.obj); // 保存详情对象

      // 处理个别数值
      const materialData = res?.obj?.purchaseNeedMaterials?.map((item: Record<string, any>) => {
        return { ...item };
      });

      setMaterialList(materialData); // 保存物料列表
    }
  });

  /** 是否显示审核弹窗 */
  const [isShowAudit, setIsShowAudit] = useState({
    isShow: false,
    selectId: '',
    type: '',
    planInfo: {},
  });

  /** 表格方法集 */
  const operateFuns = {
    /**单个审核方法*/
    onAudit: (record: Record<string, any>) => {
      setIsShowAudit({
        isShow: true,
        selectId: record?.id,
        type: 'radio',
        planInfo: recordObj,
      });
    },
    /**是否显示单个申请按钮*/
    isShowAudit: (record: Record<string, any>) => {
      return record?.prepareNum == 0 || record?.prepareNum == record?.completeNum + record?.lockNum || record?.prepareNum == record?.lockNum;
    },
    /**是否显示物料抽屉*/
    onShowDrawer: (record: Record<string, any>) => {
      setIsShowDrawer({
        isShow: true,
        id: record?.materialID,
      });
    },
  };

  /** 批量申请方法 */
  const batchAudit = () => {
    if (selectKeys?.length >= 1) {
      history.push({
        pathname: `/purchaseApplyController/addApply/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          type: 'add',
          source: 'plan',
          info: recordObj,
          supplyWay: 0,
        },
      });
    } else {
      message.warning('请选择物料！');
    }
  };

  /** 表格多选事件 */
  const onSelectChange = (key: any[]) => {
    setSelectKeys(key);
  };

  /** 初始化获取计划下物料详情列表 */
  useEffect(() => {
    if (PlanInfo?.id) {
      detailPlanRun({ id: PlanInfo?.id });
    }
  }, [PlanInfo]);

  /** 底部数量展示 */
  const tableFooterRender = () => {
    return (
      <>
        <div style={{ display: 'flex', height: '25px', alignItems: 'center', fontWeight: '600' }}>
          <p style={{ marginBottom: '0' }}>
            已采数量:&nbsp;<span style={{ color: '#1677ff' }}>{recordObj?.completeNum}</span>&nbsp;
          </p>
          &nbsp;/&nbsp;
          <p style={{ marginBottom: '0' }}>
            待采数量:&nbsp;<span style={{ color: '#1677ff' }}>{recordObj?.prepareNum}</span>&nbsp;
          </p>
        </div>
      </>
    );
  };

  /** 批量操作按钮是否显示 */
  const isShowBatchBtnMemo = useMemo(() => {
    return false;
    /** 当数据列表不存在就直接返回false */
    if (!MaterialList?.length) return false;
    /** 没有权限 */
    if (!curRes?.['/purchaseApplyController/addApply']) return false;
    /** 有数据，有权限 */
    return true;
  }, [curRes, MaterialList?.length]);

  return (
    <>
      <Card title={'计划详情'} bodyStyle={{ padding: '10px' }} className={Cls(pageStyles['page-view-cardView'], prefixCls + 'rootBox')} id={pageRouterDomID}>
        <ScrollBarLayout
          style={{
            padding: '5px 0px',
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'space-between',
          }}
        >
          {/* loading */}
          <Spin spinning={detailPlanLoading}>
            <div className={prefixCls + 'rootBox-textTitle'}>
              <Divider style={{ fontSize: '1.3rem' }}>{tooltipLength(PlanInfo?.planName, 50)}</Divider>
            </div>
            {isShowBatchBtnMemo && (
              <>
                <div
                  style={{
                    display: 'flex',
                    justifyContent: 'space-between',
                    margin: '0.2rem 1rem',
                  }}
                >
                  <Button
                    type="primary"
                    // icon={<DeliveredProcedureOutlined />}
                    style={{}}
                    onClick={batchAudit}
                  >
                    批量申请
                  </Button>
                </div>
              </>
            )}

            <div className={Cls('list-table', prefixCls + 'rootBox-materilTable')}>
              <Table
                bordered
                size="small"
                scroll={{ x: 1200, y: 1200 }}
                dataSource={MaterialList}
                columns={DetailTableColumns(curRes, operateFuns, recordObj) as any}
                rowKey={'id'}
                pagination={false}
                footer={() => {
                  return (
                    <div>
                      预估总价：<strong style={{ color: 'red' }}>{PlanInfo?.expectSum ? formatDecimal(PlanInfo?.expectSum) : 0}</strong> &nbsp;元
                    </div>
                  );
                }}
              />
            </div>
          </Spin>
        </ScrollBarLayout>

        {/* 物料详情抽屉 */}
        <MaterialDetailDrawer
          isShowDetail={isShowDrawer?.isShow}
          materialId={isShowDrawer?.id}
          pageRouterDomID={pageRouterDomID}
          onClose={() => {
            setIsShowDrawer({
              id: '',
              isShow: false,
            });
          }}
        />
      </Card>
      {isShowAudit?.isShow && (
        <AuditModal
          isShowAudit={isShowAudit}
          onClose={() => {
            setIsShowAudit({
              isShow: false,
              selectId: '',
              type: '',
              planInfo: {},
            });
          }}
          getPlanInfo={() => {
            detailPlanRun({ id: PlanInfo?.id });
            setSelectKeys([]);
          }}
        />
      )}
    </>
  );
};
export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(DetailsView);
